package easy;

public class Question14 {

    public static void main(String[] args) {
        Question14 question14 = new Question14();
        System.out.println(question14.longestCommonPrefix(new String[]{}));
        System.out.println(question14.longestCommonPrefix(new String[]{"dog", "racecar", "car"}));
    }

    public String longestCommonPrefix(String[] strs) {
        if (strs.length == 0) {
            return "";
        }
        String result = strs[0];
        for (int i = 1; i < strs.length; i++) {
            result = findCommonString(result, strs[i]);
            if (result.length() == 0) {
                return "";
            }
        }
        return result;
    }

    private String findCommonString(String shortString, String longString) {
        if (shortString.length() > longString.length()) {
            String s = shortString;
            shortString = longString;
            longString = s;
        }
        if (longString.startsWith(shortString)) {
            return shortString;
        }
        int index;
        for (index = 0; index < shortString.length(); index++) {
            if (shortString.charAt(index) != longString.charAt(index)) {
                break;
            }
        }
        return shortString.substring(0, index);
    }
}
